// 好友分组服务
import { apiService } from './api'
import type { 
  FriendGroup,
  CreateFriendGroupRequest,
  UpdateFriendGroupRequest,
  ReorderGroupsRequest,
  MoveFriendRequest,
  MoveFriendsRequest,
  FriendCountResponse
} from '@/types'

export class FriendGroupService {
  /**
   * 创建好友分组
   */
  async createGroup(request: CreateFriendGroupRequest): Promise<FriendGroup> {
    const response = await apiService.userPost<FriendGroup>('/api/friend-groups', request)
    if (!response.success || !response.data) {
      throw new Error(response.message || '创建好友分组失败')
    }
    return response.data
  }

  /**
   * 更新好友分组
   */
  async updateGroup(groupId: number, request: UpdateFriendGroupRequest): Promise<FriendGroup> {
    const response = await apiService.userPut<FriendGroup>(`/api/friend-groups/${groupId}`, request)
    if (!response.success || !response.data) {
      throw new Error(response.message || '更新好友分组失败')
    }
    return response.data
  }

  /**
   * 删除好友分组
   */
  async deleteGroup(groupId: number, userId: number): Promise<void> {
    const response = await apiService.userDelete<void>(`/api/friend-groups/${groupId}?userId=${userId}`)
    if (!response.success) {
      throw new Error(response.message || '删除好友分组失败')
    }
  }

  /**
   * 获取用户的所有分组
   */
  async getUserGroups(userId: number): Promise<FriendGroup[]> {
    const response = await apiService.userGet<FriendGroup[]>(`/api/friend-groups?userId=${userId}`)
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取好友分组失败')
    }
    return response.data
  }

  /**
   * 调整分组排序
   */
  async reorderGroups(request: ReorderGroupsRequest): Promise<void> {
    const response = await apiService.userPost<void>('/api/friend-groups/reorder', request)
    if (!response.success) {
      throw new Error(response.message || '调整分组排序失败')
    }
  }

  /**
   * 移动好友到分组
   */
  async moveFriendToGroup(request: MoveFriendRequest): Promise<void> {
    const response = await apiService.userPost<void>('/api/friend-groups/move-friend', request)
    if (!response.success) {
      throw new Error(response.message || '移动好友到分组失败')
    }
  }

  /**
   * 批量移动好友到分组
   */
  async moveFriendsToGroup(request: MoveFriendsRequest): Promise<void> {
    const response = await apiService.userPost<void>('/api/friend-groups/move-friends', request)
    if (!response.success) {
      throw new Error(response.message || '批量移动好友到分组失败')
    }
  }

  /**
   * 获取分组中的好友数量
   */
  async getFriendCountInGroup(groupId: number, userId: number): Promise<number> {
    const response = await apiService.userGet<FriendCountResponse>(
      `/api/friend-groups/${groupId}/friend-count?userId=${userId}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取分组好友数量失败')
    }
    return response.data.count
  }

  /**
   * 获取带好友数量的分组列表
   */
  async getUserGroupsWithCount(userId: number): Promise<FriendGroup[]> {
    const groups = await this.getUserGroups(userId)
    
    // 并发获取每个分组的好友数量
    const groupsWithCount = await Promise.all(
      groups.map(async (group) => {
        try {
          const count = await this.getFriendCountInGroup(group.id, userId)
          return { ...group, friendCount: count }
        } catch (error) {
          console.error(`Failed to get friend count for group ${group.id}:`, error)
          return { ...group, friendCount: 0 }
        }
      })
    )

    return groupsWithCount
  }

  /**
   * 创建默认分组
   */
  async createDefaultGroup(userId: number): Promise<FriendGroup> {
    const request: CreateFriendGroupRequest = {
      userId,
      name: '我的好友',
      description: '默认好友分组'
    }
    return this.createGroup(request)
  }

  /**
   * 检查分组名称是否可用
   */
  async isGroupNameAvailable(userId: number, name: string, excludeGroupId?: number): Promise<boolean> {
    try {
      const groups = await this.getUserGroups(userId)
      return !groups.some(group => 
        group.name === name && group.id !== excludeGroupId
      )
    } catch (error) {
      console.error('Error checking group name availability:', error)
      return false
    }
  }

  /**
   * 获取默认分组
   */
  async getDefaultGroup(userId: number): Promise<FriendGroup | null> {
    try {
      const groups = await this.getUserGroups(userId)
      return groups.find(group => group.isDefault) || null
    } catch (error) {
      console.error('Error getting default group:', error)
      return null
    }
  }

  /**
   * 批量创建分组
   */
  async batchCreateGroups(
    userId: number, 
    groupNames: string[]
  ): Promise<{ success: FriendGroup[]; failed: string[]; errors: string[] }> {
    const results = {
      success: [] as FriendGroup[],
      failed: [] as string[],
      errors: [] as string[]
    }

    const promises = groupNames.map(async (name) => {
      try {
        const group = await this.createGroup({
          userId,
          name,
          description: `分组: ${name}`
        })
        results.success.push(group)
      } catch (error) {
        results.failed.push(name)
        results.errors.push(`${name}: ${error instanceof Error ? error.message : '未知错误'}`)
      }
    })

    await Promise.allSettled(promises)
    return results
  }
}

export const friendGroupService = new FriendGroupService()